package net.ojbk.sso.center.beans.pojo;

import net.ojbk.sso.center.beans.po.ClientWebsite;
import net.ojbk.sso.center.dao.ClientWebsiteDao;
import net.ojbk.sso.center.util.RandomStringTool;
import net.ojbk.sso.core.beans.dto.DTO_TO_Center;
import net.ojbk.sso.core.exception.ClientWebException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/3/23
 * Time: 21:28
 * Description: 维护所有客户网站相关的业务.管理网站实体、以及与网站通信的DTO
 */
@Configuration
public class ClientWebSystem {
    private static Logger logger = Logger.getLogger(ClientWebSystem.class);
    private ClientWebsiteDao clientWebsiteDao;
    // 0 类属性
    private Map<String, ClientWebsite> clientWebsiteMap;

    // 1 构造器相关
    @Autowired
    public ClientWebSystem(ClientWebsiteDao clientWebsiteDao) {
        this.clientWebsiteDao = clientWebsiteDao;
        // Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
        clientWebsiteMap = clientWebsiteDao.selectAll().stream().collect(Collectors.toMap(ClientWebsite::getCname, a -> a, (v1, v2) -> v2));
        if (clientWebsiteMap == null) {
            logger.error("nameClientWebsiteMap obtained through dao are null.");
            clientWebsiteMap = new HashMap<>();
        }
    }

    // 2 验证
    // 2.1 验证DTO_TO_Center的真实性
    public boolean isLegalDTO(DTO_TO_Center dto_to_center) {
        ClientWebsite clientWebsite = clientWebsiteMap.get(dto_to_center.getCname());
        if (clientWebsite == null || !clientWebsite.getIp().equals(dto_to_center.getIp()) || !clientWebsite.getClientKey().equals(dto_to_center.getClientKey()))
            return false;
        return true;
    }
    // 2.2 验证 该cname是否是该 uid的
    public boolean isUsersWeb(String uid, String cname) throws Exception {
        ClientWebsite website = getClientWebsite_ByCname(cname);
        if (website.getUid().equals(uid))
            return true;
        return false;
    }

    // 3 动作

    /**
     * 3.1 一个人登记一个网站
     *
     * @param userId    一个人
     * @param cname     新网站的名字
     * @param clientUrl 新网站的对面URL接口地址
     * @throws Exception 网站已存在、cname不符合要求、其他：登记失败
     */
    public void registerNewWebsite(String userId, String cname, String clientUrl) throws Exception {
        // 判断此名字是否已存在
        if (clientWebsiteMap.get(cname) != null)
            throw new ClientWebException("Sorry, the cname exists.");
        // 必须要是四位字符
        if (cname.length() != 4)
            throw new ClientWebException("The cname is not four characters.");
        ClientWebsite newWebsite = new ClientWebsite();
        newWebsite.setUid(userId);
        newWebsite.setCname(cname);
        newWebsite.setClientUrl(clientUrl);
        URI uri = URI.create(clientUrl);
        newWebsite.setIp(InetAddress.getByName(uri.getHost()).getHostAddress());
        newWebsite.setClientKey(RandomStringTool.getRandomString(RandomStringTool.CHARS_majuscule + RandomStringTool.CHARS_Lowercase_Letters + RandomStringTool.CHARS_number, 4));
        newWebsite.setServiceKey(RandomStringTool.getRandomString(RandomStringTool.CHARS_majuscule + RandomStringTool.CHARS_Lowercase_Letters + RandomStringTool.CHARS_number, 4));
        newWebsite.setState(1);
        newWebsite.setRegistrationTime(new Date());
        clientWebsiteDao.insertOne(newWebsite);
        clientWebsiteMap.put(cname, newWebsite);
    }

    /**
     * 3.2 升级一个网站的IP地址。
     *
     * @param cname 新网站的名称
     */
    public void updateWebIp(String cname, String newIp) throws ClientWebException {
        ClientWebsite website = getClientWebsite_ByCname(cname);
        website.setIp(newIp);
        clientWebsiteDao.updateOne(website);
    }

    /**
     * 3.3 一键通过DNS获取ip并绑定到验证ip
     */
    public void updateWebIp(String cname) throws Exception {
        ClientWebsite website = getClientWebsite_ByCname(cname);

        URI uri = URI.create(website.getClientUrl());
        website.setIp(InetAddress.getByName(uri.getHost()).getHostAddress());
        clientWebsiteDao.updateOne(website);
    }

    /**
     * 3.4 删除一个web，原来以及登陆此web的人不受影响。下次登陆起起效。
     */
    public void deleteWeb(String cname) throws ClientWebException {
        ClientWebsite website = getClientWebsite_ByCname(cname);
        // 数据库中删除
        clientWebsiteDao.deleteOne(website);
        // map中删除
        clientWebsiteMap.remove(website.getCname());
    }

    // 4 获取信息
    public ClientWebsite getClientWebsite_ByCname(String cname) throws ClientWebException {
        ClientWebsite clientWebsite = clientWebsiteMap.get(cname);
        if (clientWebsite == null)
            throw new ClientWebException("The clientWebsite does not exist.");
        return clientWebsite;
    }

    public String getServiceKey_ByCname(String cname) throws ClientWebException {
        return getClientWebsite_ByCname(cname).getServiceKey();
    }


//
//    public boolean existWeb(String cname) {
//        ClientWebsite website = nameClientWebsiteMap.get(cname);
//        if (website == null)
//            return false;
//        return true;
//    }
}
